import * as React from "react";
import { List } from "antd-mobile";

const { Item } = List;

export default class Rolelist extends React.Component {
  static getDerivedStateFromProps(nextProps) {
    const { value } = nextProps;
    if (value) {
      return {
        selected: value,
      };
    }
    return null;
  }

  state = {
    selected: this.props.value || [],
  };

  render() {
    const { selected } = this.state;
    const { onChange, data } = this.props;
    const changeSelect = (val) => {
      this.setState({
        selected: val,
      });
      onChange(val);
    };
    return (
      <List style={{ width: '100%' }} renderHeader="审批人">
        {data.map((contact) => (
          <Item
            thumb={contact.icon}
            key={contact.id}
            onClick={() => {
              const index = selected.findIndex((i) => i === contact.id);
              if (index > -1) {
                const temp = selected;
                temp.splice(index, 1);
                changeSelect(temp);
              } else {
                const newArray = [ ...selected, contact.id ];
                changeSelect(newArray);
              }
            }}
            extra={
              <img
                alt=""
                src={`${
                  selected.findIndex((i) => i === contact.id) > -1
                    ? `${process.env.PUBLIC_URL}./assets/img/selected.png`
                    : `${process.env.PUBLIC_URL}./assets/img/unselected.png`
                }`}
              />
            }
          >
            {contact.name}
          </Item>
        ))}
      </List>
    );
  }
}
